package router

import (
	"net/http"
	"sep22-hw/handler"

	"github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

func Init() *gin.Engine {
	r := gin.Default()

	r.Use(Cors())

	r.Static("/static", "./static")

	r.POST("/login", handler.Login)  //登录
	r.GET("/list", handler.List)     //列表
	r.GET("/select", handler.Select) //查询

	r.GET("/userRole", handler.UserRole)             //用户角色表
	r.GET("/userRoleSelect", handler.UserRoleSelect) //用户角色查询

	r.GET("/roleNode", handler.RoleNode)             //角色权限表
	r.GET("/roleNodeSelect", handler.RoleNodeSelect) //角色权限查询
	return r
}
